<?php
namespace app\libs;
use app\modules\cn\models\User;
use yii;
use app\modules\cn\models\IpLimit;
use app\modules\cn\models\Phone;
use app\modules\cn\models\SslToken;

use yii\data\Pagination;
class Method
{
    private static $code;//验证码
    private  static$charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子
    /**
     * 分页函数
     * @param array $config 分页配置
     * @return array 分页
     * @Obelisk
     */
    public static function getPagedRows($config = [])
    {
        $pages = new Pagination(['totalCount' => $config['count']]);
        if (isset($config['pageSize'])) {
            $pages->setPageSize($config['pageSize'], true);
        }
        return $pages;
    }

    public static function getPlayUrl($time){

        $playData = Yii::$app->cache->get('player2ielts');
        if(!$playData){
            $times = date("Y-m-d H:i:s",time()+$time);
            $times = strtoupper(base_convert(strtotime($times),10,16));
            $stream  = "live-ielts";
            $txSecret = md5("Tbc123edsss".$stream.$times);
            $url = "webrtc://play.viplgw.cn/live/$stream?txSecret=$txSecret&txTime=$times";
            $rtmpUrl = "rtmp://play.viplgw.cn/live/$stream?txSecret=$txSecret&txTime=$times";
            $flvUrl = "https://play.viplgw.cn/live/$stream.flv?txSecret=$txSecret&txTime=$times";
            $length = rand(4,6);
            self::createCode($length);
            $url = base64_encode($url).self::$code;
            $rtmpUrl = base64_encode($rtmpUrl).self::$code;
            $flvUrl = base64_encode($flvUrl).self::$code;
            $playData = ['url' => $url,'length' => $length,'rtmpUrl' => $rtmpUrl,'flvUrl' => $flvUrl];
            Yii::$app->cache->set('player2ielts',$playData,$time-7200);
        }
        return $playData;
    }

    //生成随机码
    private static function createCode($length) {
        $_len = strlen(self::$charset)-1;
        for ($i=0;$i<$length;$i++) {
            self::$code .= self::$charset[mt_rand(0,$_len)];
        }
    }

    public static function addDomainToImgSrc($content, $domain)
    {
        // 正则表达式匹配<img>标签中的src属性
        $pattern = '/<img[^>]+src="([^"]*)"[^>]*>/i';

        // 使用回调函数处理匹配到的内容
        $content = preg_replace_callback($pattern, function ($matches) use ($domain) {
            $src = $matches[1];

            // 如果src没有域名，则添加域名
            if (!preg_match('/^https?:\/\//i', $src)) {
                $src = $domain . $src;
            }

            // 返回替换后的<img>标签
            return str_replace($matches[1], $src, $matches[0]);
        }, $content);

        return $content;
    }

    public static function curl_post_fix($url,$data){
        $url = str_replace(' ','+',$url);

        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, "$url");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        //执行并获取url地址的内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }

        /**
    * 接口字符串
    * @param $code
    * @param $data
    * @param $message
    * @return string
    * @Obelisk
    */
    public static function jsonGenerate($code,$data=null,$message='success'){
        return json_encode(['code' => $code,'data' => $data,'message' => $message]);
    }

    public static function curl_post_jason($url,$json_data){
        $headers = array(
            "Content-Type: application/json",
            "Content-Length: " . strlen($json_data)
        );

// 初始化cURL
        $ch = curl_init();

// 设置请求参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// 执行请求并获取响应
        $response = curl_exec($ch);

// 关闭cURL资源
        curl_close($ch);
        return $response;
    }


// 发送模板消息
    public static function sendTemplateMessage($access_token, $touser, $template_id, $data, $url = '') {
        $apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
        $postData = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'data' => $data
        );
        $postData = json_encode($postData, JSON_UNESCAPED_UNICODE);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }

    //获取token,设置有效期,保存到cache
    public static function token()
    {
        $token = Yii::$app->cache->get('wx_token');
        if(!$token){
            $getAccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc5a6082e703c586d&secret=6ee16eb5dcbf8c9399d351330b916f12';
            $rs = json_decode(file_get_contents($getAccessTokenUrl), true);
            if (!empty($rs['access_token'])) {
                Yii::$app->cache->set('wx_token', $rs['access_token'],7180);//保存的参数有点问题到时候要修改
            }
            $token = $rs['access_token'];
        }
        return $token;
    }

    /**
     * 生成32位字符串
     * @return string
     * @Obelisk
     */
    public static function guid()
    {
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        $uuid = substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
        return $uuid;
    }

    /**
     * 表格数据导入
     * @param $file
     * @return array
     */
    public static function importExcel($file,$start=1){
        ini_set("memory_limit",-1);
        set_time_limit(0);
        date_default_timezone_set('PRC');
        header("Content-type: text/html; charset=utf-8");
        include_once "../libs/PHPExcel.class.php";//引入phpexcel
        $file = iconv("utf-8", "gb2312", $file);  //转码
        if($file&&$file[0] == '/'){
            $file  = substr($file,1);
        }
        if(empty($file) OR !file_exists($file)) {
            return ['code'=>0,'message'=>'file not exists!'];
        }
        $objRead = new \PHPExcel_Reader_Excel2007(); //建立reader对象
        if(!$objRead->canRead($file)){
            $objRead = new \PHPExcel_Reader_Excel5();
            if(!$objRead->canRead($file)){
                return ['code'=>0,'message'=>'No Excel!'];
            }
        }
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $sheet = 0;
        $obj = $objRead->load($file);  //建立excel对象
        $currSheet = $obj->getSheet($sheet);   //获取指定的sheet表
        $columnH = $currSheet->getHighestColumn();   //取得最大的列号
        $columnCnt = array_search($columnH, $cellName);
        $columnCnt = $columnCnt?$columnCnt:51;//超过最大列
        $rowCnt = $currSheet->getHighestRow();   //获取总行数
        $data = array();
        for($_row=$start; $_row<=$rowCnt; $_row++){  //读取内容
            for($_column=0; $_column<=$columnCnt; $_column++){
                $cellId = $cellName[$_column].$_row;
                $cellValue = $currSheet->getCell($cellId)->getValue();
                //$cellValue = $currSheet->getCell($cellId)->getCalculatedValue();  #获取公式计算的值
                if($cellValue instanceof \PHPExcel_RichText){   //富文本转换字符串
                    $cellValue = $cellValue->__toString();
                }
                $data[$_row][$cellName[$_column]] = $cellValue;
            }
        }
        return ['code'=>1,'data'=>$data];
    }

    /**
     * 生成订单号
     * @return string
     * @Obelisk
     */
    public static function orderNumber()
    {
        $orderNumber = 'sy'.time().rand(0,9);
        return $orderNumber;
    }

    /**
     * @param string $html html内容
     * @param string $tags 保留标签
     * @return string
     */
    public static function getextbyhtml($html = '', $tags = '')
    {
        if (!empty($html)) {
            $res = preg_replace('/&nbsp;/', ' ', trim(strip_tags(htmlspecialchars_decode($html), $tags)));
            $res = trim(preg_replace('/<(p|P)>\W+<\/(p|P)>/', '', $res));
        } else {
            $res = false;
        }
        return $res;
    }

    /**
     * 词典翻译
     * @Obelisk
     */
    public static function getTranslate($words){
        $url = "http://fanyi.youdao.com/openapi.do?keyfrom=5asdfasdf6&key=925644231&type=data&only=dict&doctype=json&version=1.1&q=".$words;
        $list = file_get_contents($url);
        $js_de = json_decode($list,true);
        if($js_de['errorCode'] != 0){
            $data = 0;
        }else{
            $js_de['basic']['us'] = $js_de['basic']['us-phonetic'];
            $js_de['basic']['uk'] = $js_de['basic']['uk-phonetic'];
            $data = $js_de['basic'];
        }
        return $data;
    }

    /**
     * post请求
     * @param $url
     * @param string $post_data
     * @param int $timeout
     * @return mixed
     * @Obelisk
     */
    public static  function post($url, $post_data = '', $timeout = 5){//curl

        $ch = curl_init();

        curl_setopt ($ch, CURLOPT_URL, $url);

        curl_setopt ($ch, CURLOPT_POST, 1);

        if($post_data != ''){

            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

        }

        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_HEADER, false);

        $file_contents = curl_exec($ch);

        curl_close($ch);

        return $file_contents;

    }

   public static function curl_post($url,$data){
        $url = str_replace(' ','+',$url);

        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, "$url");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        //执行并获取url地址的内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return $output;
    }


    /**
     * 获取IP信息
     * @Obelisk
     */
    public static function getIpInfo($ip){
        $datatype = 'jsonp';
        $url = 'http://api.ip138.com/query/?ip='.$ip.'&datatype='.$datatype;
        $header = array('token:cb2239f986b33696c592d0630b89fd90');
        $data = json_decode(self::getData($url,$header),true);
        if($data['ret'] == 'ok'){
            return $data['data'];
        }else{
            return [1=>''];
        }
    }

    private static function getData($url,$header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        $handles = curl_exec($ch);
        curl_close($ch);
        return $handles;
    }

    public static function  getBroswer()
{
    $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
    if (stripos($sys, "Firefox/") > 0) {
        preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
        $exp[0] = "Firefox";
        $exp[1] = $b[1];  //获取火狐浏览器的版本号
    } elseif (stripos($sys, "Maxthon") > 0) {
        preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
        $exp[0] = "傲游";
        $exp[1] = $aoyou[1];
    } elseif (stripos($sys, "MSIE") > 0) {
        preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
        $exp[0] = "IE";
        $exp[1] = $ie[1];  //获取IE的版本号
    } elseif (stripos($sys, "OPR") > 0) {
        preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
        $exp[0] = "Opera";
        $exp[1] = $opera[1];
    } elseif (stripos($sys, "Edge") > 0) {
        //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
        preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
        $exp[0] = "Edge";
        $exp[1] = $Edge[1];
    } elseif (stripos($sys, "Chrome") > 0) {
        preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
        $exp[0] = "Chrome";
        $exp[1] = $google[1];  //获取google chrome的版本号
    } elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
        preg_match("/rv:([\d\.]+)/", $sys, $IE);
        $exp[0] = "IE";
        $exp[1] = $IE[1];
    } else {
        $exp[0] = "未知浏览器";
        return $exp[0];
    }
    return $exp[0] ;
}


    /**
     * 验证短信码
     * @param $code
     * @Obelisk
     */
    public static function checkCode($phone,$code){
        $phoneCode = \Yii::$app->session->get($phone.'phoneCode');
        if($phoneCode == $code){
            \Yii::$app->session->remove($phone.'phoneCode');
            $re = true;
        }else{
            $re = false;
        }
        return $re;
    }

    /**
     * 验证短信的时间是否过期
     * @Obelisk
     */
    public static function checkTime(){
        $phoneTime = \Yii::$app->session->get('phoneTime');
        $timeLimit = \Yii::$app->params['timeLimit'];
        if(time()-$phoneTime>$timeLimit){
            $re = false;
        }else{
            $re = true;
        }
        return $re;
    }

    /**
     * 页码的数组
     * @Obelisk
     */
    public static function page($countPage,$page)
    {
        $pageArray=array();
        if ($countPage > 1) {
            for ($i = 1; $i <= $countPage; $i++) {
                if($countPage<7){
                    array_push($pageArray,$i);
                }else{
                    if($page<3){
                        if($i<6)
                        array_push($pageArray,$i);
                        if($i==6){
                            array_push($pageArray,'...');
                            array_push($pageArray,$countPage);
                            break;
                        }
                    }else{
                        if ($countPage - $page <= 4) {
                            if ($i == 1) {
                                array_push($pageArray, 1);
                                array_push($pageArray, '...');
                            }
                            if ($i <= $countPage && $i >= $countPage - 4) {
                                array_push($pageArray, $i);
                            }
                        }else{
                            if ($i == 1) {
                                array_push($pageArray, 1);
                                array_push($pageArray, '...');
                            }
                            if ($i >= $page && $i <= $page + 3) {
                                array_push($pageArray, $i);
                            }
                            if ($i ==$countPage) {
                                array_push($pageArray, '...');
                                array_push($pageArray, $countPage);
                                break;
                            }
                        }

                    }

                }
             }
        }
        return $pageArray;
    }

    /**
     * 短信限制
     * @Obelisk
     */
    public static function confirmPhone($ip,$phone,$belong){
        $date = date("Y-m-d");
        $time = time();
        $sign = true;
        $content = '';
        $phoneNum = Phone::find()->where("phone='$phone' AND dateTime='$date'")->count();
//        if($phoneNum >=5){
//            $sign = false;
//            $content = '当前地址每日最多发送五条';
//        }
        $phoneTime = Phone::find()->asArray()->where("phone='$phone'")->orderBy("createTime DESC")->one();
        if($phoneTime){
            $phoneTime = $phoneTime['createTime'];
        }else{
            $phoneTime = 0;
        }
//        if($time-$phoneTime <= 120){
//            $sign = false;
//            $content = '两分钟内不重复发送';
//        }
//    var_dump($phoneNum);die;
        $ipNum = IpLimit::find()->where("ip='$ip' AND dateTime='$date'")->count();

//        if($ipNum >=5){
//            $sign = false;
//            $content = '当前地址每日最多发送五条';
//        }
        $ipTime = IpLimit::find()->asArray()->where("ip='$ip'")->orderBy("createTime DESC")->one();
        if($ipTime){
            $ipTime = $ipTime['createTime'];
        }else{
            $ipTime = 0;
        }
//        if($time-$ipTime <= 120){
//            $sign = false;
//            $content = '两分钟内不重复发送';
//        }
        if($sign){
            $model = new Phone();
            $model->phone = $phone;
            $model->dateTime = $date;
            $model->createTime = $time;
            $model->save();
            $model = new IpLimit();
            $model->ip = $ip;
            $model->dateTime = $date;
            $model->createTime = $time;
            $model->belong = $belong;
            $model->save();
        }
        return ['sign' => $sign,'content' => $content];
    }

    public static function getNickanme(){
        $str = intval(time()/rand(1000,9999));
        for ($i = 1; $i <= 4; $i++) {
            $str .= chr(rand(97, 122));
        }
        return $str;
    }


     /**
     * 验证用户
     */
    public static function confim_user($data){
        $uid = $data['uid'];
        $phone = $data['phone'];
        $email = $data['email'];
        $nickname = $data['nickname'];
        $username = $data['username'];
        $user = User::find()->where("uid=$uid")->one();
        if($user){
            $userId = $user['id'];
            if($phone != $user['phone']){
                User::updateAll(['phone' => $phone],"id=$userId");
            }
            if($email != $user['email']){
                User::updateAll(['email' => $email],"id=$userId");
            }
            if($nickname != $user['nickname']){
                User::updateAll(['nickname' => $nickname],"id=$userId");
            }
            if($username != $user['userName']){
                User::updateAll(['userName' => $username],"id=$userId");
            }
            if ($user['createTime'] == false) {
                User::updateAll(['createTime' => time()], "id=$userId");
            }
        }else{
            $model = new User();
            $model->userName = $username;
            $model->nickname = $nickname;
            $model->email = $email;
            $model->userPass = '';
            $model->phone = $phone;
            $model->createTime = time();
            $model->lastSign =time();
            $model->uid = $uid;
            $model->save();
            $userId = $model->primaryKey;
        }

        
        $user = User::find()->where("id=$userId")->asArray()->one();
        Yii::$app->session->set('userId',$userId);
        Yii::$app->session->set("userData",$user);
        Yii::$app->session->set("uid",$uid);
        Yii::$app->session->set("level",$data['level']);
    }

    /**
     * web验证用户
     *         传值： token
     */


    public static function webcheck($token){   
        // $request = Yii::$app->request;
        // $token = $request->post('token',111);
        // $ip = $request->post('ip');
        $time = time();
        // $token ='10bd70e4ef1118c28e6318d74e33c5b1';
        $res = SslToken::find()->where("token='$token'")->asArray()->one();
        $uid = 0;
        // var_dump($token);die;
        if($res){
            if($token == md5($res['uid'].$res['updateTime'])){
                $uid = $res['uid'];
            }
            if($token == $res['token']){
                $uid = $res['uid'];
            }
        }elseif(!empty($ip)){
            $res = SslToken::find()->where("ip='$ip'")->asArray()->one();
            if($time-$res['updateTime']<8){
                $uid = $res['uid'];
            }
        }
        if($uid){
            list($uid,$username,$email,$phone,$nickname,$level) = uc_get_user($uid,1);
            $re = [
                'code' => 1,
                'info' => [
                    'uid' => $uid,
                    'username' => $username,
                    'email' => $email,
                    'phone' => $phone,
                    'nickname' => $nickname,
                    'level' => $level,
                ],
            ];
        }else{
            $re = [
                'code' => 0,
                'info' => null,
            ];
        }

        return $re;
        // die(json_encode($re));
    }



}
